package com.weaver.qfengx.demo.createwf;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import cn.hutool.crypto.asymmetric.RSA;


import java.util.Map;
import java.util.Objects;

/**
 * @Description 创建流程完整示例
 * @Author Qfengx <qffg1998@126.com>
 * @Date 2021-07-28 09:48:31
 */
public class Demo {

    private static final String APPID = "9aebc1b4-6f35-5454-81a1-325001a7685b";
    private static final String ECURL = "http://10.101.240.38";
    private static final Map<String, String> SYSTEM_CACHE = Maps.newHashMap();
    private static final String SERVER_PUBLIC_KEY = "SERVER_PUBLIC_KEY";
    private static final String SERVER_SECRET = "SERVER_SECRET";
    private static final String SERVER_TOKEN = "SERVER_TOKEN";

    public static void main(String[] args) {
        // 业务相关数据
        String userid = "7048";
        String createWfUrl = "/api/workflow/paService/doCreateRequest";
        Map<String, Object> paramMap = Maps.newHashMap();
        JSONArray mainDataArr = new JSONArray();
        // 设置费用类别字段
        mainDataArr.add(createField("fylb", "2"));
        // 设置事项类别字段
        mainDataArr.add(createField("sxlb", "0"));

        paramMap.put("mainData", mainDataArr.toJSONString());
        JSONArray dtArr = new JSONArray(); // 明细表数据
        paramMap.put("detailData", dtArr.toJSONString());
        paramMap.put("requestName", "流程请求标题");
        paramMap.put("workflowId", 604);

        // 接口请求
        //ECOLOGY返回的token
        String token = getToken();

        String spk = SYSTEM_CACHE.get(SERVER_PUBLIC_KEY);
        //封装请求头参数
        RSA rsa = new RSA(null, spk);
        //对用户信息进行加密传输,暂仅支持传输OA用户ID
        String encryptUserid = rsa.encryptBase64(userid, CharsetUtil.CHARSET_UTF_8, KeyType.PublicKey);

        //调用ECOLOGY系统接口
        String data = HttpRequest.post(ECURL + createWfUrl)
                .header("appid", APPID)
                .header("token", token)
                .header("userid", encryptUserid)
                // ！！！！！注意这是form,这是form,这是form,重要的事情说三遍
                .form(paramMap)
                .execute().body();

        System.out.println("createWfRes => " + data);
    }

    // 创建普通的字段
    private static JSONObject createField(String fieldname, String fieldval) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("fieldName", fieldname);
        jsonObject.put("fieldValue", fieldval);
        return jsonObject;
    }

    public static String getToken() {
        String secret = SYSTEM_CACHE.get(SERVER_SECRET);
        String spk = SYSTEM_CACHE.get(SERVER_PUBLIC_KEY);
        // 如果为空,说明还未进行注册,调用注册接口进行注册认证与数据更新
        if (Objects.isNull(secret) || Objects.isNull(spk)) {
            register();
            // 重新获取最新ECOLOGY系统公钥和Secret信息
            secret = SYSTEM_CACHE.get(SERVER_SECRET);
            spk = SYSTEM_CACHE.get(SERVER_PUBLIC_KEY);
        }
        // 公钥加密,所以RSA对象私钥为null
        RSA rsa = new RSA(null, spk);
        //对秘钥进行加密传输，防止篡改数据
        String encryptSecret = rsa.encryptBase64(secret, CharsetUtil.CHARSET_UTF_8, KeyType.PublicKey);

        //调用ECOLOGY系统接口进行注册
        String data = HttpRequest.post(ECURL + "/api/ec/dev/auth/applytoken")
                .header("appid", APPID)
                .header("secret", encryptSecret)
                .header("time", "3600")
                .execute().body();

        System.out.println("tokenjson => " + data);
        Map<String, Object> datas = JSONUtil.parseObj(data);

        //ECOLOGY返回的token
        // TODO 为Token缓存设置过期时间
        SYSTEM_CACHE.put("SERVER_TOKEN", StrUtil.nullToEmpty((String) datas.get("token")));

        return SYSTEM_CACHE.get(SERVER_TOKEN);
    }

    private static Map<String, Object> register() {
        RSA rsa = new RSA();
        String publicKey = rsa.getPublicKeyBase64();
        String privateKey = rsa.getPrivateKeyBase64();

        // 客户端RSA私钥
        SYSTEM_CACHE.put("LOCAL_PRIVATE_KEY", privateKey);
        // 客户端RSA公钥
        SYSTEM_CACHE.put("LOCAL_PUBLIC_KEY", publicKey);
        //调用ECOLOGY系统接口进行注册
        String data = HttpRequest.post(ECURL + "/api/ec/dev/auth/regist")
                .header("appid", APPID)
                .header("cpk", publicKey)
                .timeout(2000)
                .execute().body();

        // 打印ECOLOGY响应信息
        System.out.println("register => " + data);
        Map<String, Object> datas = JSONUtil.parseObj(data);

        //ECOLOGY返回的系统公钥
        SYSTEM_CACHE.put(SERVER_PUBLIC_KEY, StrUtil.nullToEmpty((String) datas.get("spk")));
        //ECOLOGY返回的系统密钥
        SYSTEM_CACHE.put(SERVER_SECRET, StrUtil.nullToEmpty((String) datas.get("secrit")));
        return datas;
    }

}
